<template>
  <div class="home">
    <a-card title="用户管理" style="width: 100%">
      <template #extra>
        <a-button type="primary" @click="showModal">新增用户</a-button>
      </template>
      
      <a-table :columns="columns" :data-source="dataSource" rowKey="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="editUser(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这条记录吗？"
                @confirm="deleteUser(record.id)"
              >
                <a style="color: #ff4d4f">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <a-button type="primary" html-type="submit"  @click="toApp3">跳转子应用3</a-button>
      <a-button type="primary" html-type="submit"  @click="toHome" style="margin-left: 10px;">跳转主应用</a-button>
    </a-card>

    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { storage } from '../utils/storage';

interface UserData {
  id: number;
  username: string;
  email: string;
  role: string;
}

const STORAGE_KEY = 'users';

const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '角色',
    dataIndex: 'role',
    key: 'role',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const dataSource = ref<UserData[]>([]);

const toApp3 = () => {
    window.history.pushState({}, '', '/app3/#/');
};

const toHome = () => {
    window.history.pushState({}, '', '/productRequire/productRequirements');
};
// 从本地存储加载数据
onMounted(() => {
  const savedUsers = storage.getItem<UserData[]>(STORAGE_KEY);
  if (savedUsers) {
    dataSource.value = savedUsers;
  } else {
    // 初始数据
    dataSource.value = [
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        role: 'admin',
      },
    ];
    // 保存到本地存储
    storage.setItem(STORAGE_KEY, dataSource.value);
  }
});

const modalVisible = ref(false);
const modalTitle = ref('新增用户');
const formRef = ref<FormInstance>();
const formState = reactive({
  username: '',
  email: '',
  role: 'user',
});

const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '请输入有效的邮箱地址' }
  ],
  role: [{ required: true, message: '请选择角色' }],
};

const showModal = () => {
  modalTitle.value = '新增用户';
  formState.username = '';
  formState.email = '';
  formState.role = 'user';
  modalVisible.value = true;
};

const editUser = (record: UserData) => {
  modalTitle.value = '编辑用户';
  formState.username = record.username;
  formState.email = record.email;
  formState.role = record.role;
  modalVisible.value = true;
};

const deleteUser = (id: number) => {
  dataSource.value = dataSource.value.filter(item => item.id !== id);
  // 更新本地存储
  storage.setItem(STORAGE_KEY, dataSource.value);
};

const handleOk = () => {
  formRef.value?.validate().then(() => {
    if (modalTitle.value === '新增用户') {
      const newUser = {
        id: Date.now(),
        ...formState,
      };
      dataSource.value.push(newUser);
    } else {
      const index = dataSource.value.findIndex(item => item.username === formState.username);
      if (index !== -1) {
        dataSource.value[index] = { ...dataSource.value[index], ...formState };
      }
    }
    // 更新本地存储
    storage.setItem(STORAGE_KEY, dataSource.value);
    modalVisible.value = false;
  });
};

const handleCancel = () => {
  modalVisible.value = false;
};
</script>